package com.lagou.oss.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.lagou.oss.config.AliyunConfig;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName AliyunUploader
 * @Description TODO
 * @Author xsq
 * @Date 2020/9/22 10:30
 **/
@Service
public class AliyunUploader {

    @Autowired
    private OSS ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    public void upload(byte[] data,String objName){
        ossClient.putObject(aliyunConfig.getBucketName(),objName,new ByteArrayInputStream(data));
    }

    public byte[] download(String objName) throws IOException {
        OSSObject object = ossClient.getObject(aliyunConfig.getBucketName(), objName);

        InputStream objectContent = object.getObjectContent();

        if (objectContent != null) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            IOUtils.copy(objectContent, output);
            objectContent.close();
            return output.toByteArray();
        }
        return null;
    }

    public void delete(String objName){
        ossClient.deleteObject(aliyunConfig.getBucketName(),objName);
    }

}
